package cn.net.xyan.tts.api;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import java.io.ByteArrayInputStream;

/**
 * Created by zarra on 2017/1/25.
 */
public class WaveFormat {
    int avgBytesPerSec;
    short bitsPerSample;
    int samplesPerSec;
    short blockAlign;
    short channels;
    short formatTag;

    public WaveFormat(){

    }

    public WaveFormat(int sampleRate,int channels,int bitsPerSample){
        this.samplesPerSec = sampleRate;
        this.channels = (short)channels;
        this.bitsPerSample = (short)bitsPerSample;

        avgBytesPerSec = sampleRate*channels*bitsPerSample/8;

        formatTag=1;
        blockAlign = (short) (bitsPerSample/8);
    }

    public int getAvgBytesPerSec() {
        return avgBytesPerSec;
    }

    public void setAvgBytesPerSec(int avgBytesPerSec) {
        this.avgBytesPerSec = avgBytesPerSec;
    }

    public short getBitsPerSample() {
        return bitsPerSample;
    }

    public void setBitsPerSample(short bitsPerSample) {
        this.bitsPerSample = bitsPerSample;
    }

    public int getSamplesPerSec() {
        return samplesPerSec;
    }

    public void setSamplesPerSec(int samplesPerSec) {
        this.samplesPerSec = samplesPerSec;
    }

    public short getBlockAlign() {
        return blockAlign;
    }

    public void setBlockAlign(short blockAlign) {
        this.blockAlign = blockAlign;
    }

    public short getChannels() {
        return channels;
    }

    public void setChannels(short channels) {
        this.channels = channels;
    }

    public short getFormatTag() {
        return formatTag;
    }

    public void setFormatTag(short formatTag) {
        this.formatTag = formatTag;
    }

    public AudioFormat toAudioFormat(){
        AudioFormat format = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, samplesPerSec,
                bitsPerSample, channels, channels *  bitsPerSample / 8, avgBytesPerSec,
                false);
        return format;
    }

    public AudioInputStream createAudioInputStream(byte[] audioData){
        AudioInputStream stream = new AudioInputStream(new ByteArrayInputStream(audioData), toAudioFormat(), audioData.length*8/bitsPerSample);
        return stream;
    }

    @Override
    public String toString() {
        return "WaveFormat{" +
                "avgBytesPerSec=" + avgBytesPerSec +
                ", bitsPerSample=" + bitsPerSample +
                ", samplesPerSec=" + samplesPerSec +
                ", blockAlign=" + blockAlign +
                ", channels=" + channels +
                ", formatTag=" + formatTag +
                '}';
    }
}
